// pages/detail/detail.js
const db = wx.cloud.database();
const app = getApp();
const computedBehavior = require("miniprogram-computed").behavior;
const chapterCollection = "chapters";
Page({
  behaviors: [computedBehavior],
  options: {
    "styleIsolation": 'apply-shared',
  },
  /**
   * 页面的初始数据
   */
  data: {
    bookInfo: {},
    id: "",
    title: "",
    img: "",
    comments: [],
    isInBookself: false,
    readPage: 0,
    user: {}
  },
  computed: {
    img(data) {
      let list = [];
      data?.bookInfo?.link?.forEach(el => {
        if (el.type == "image/png") {
          list.push(el);
        }
      })
      return list[0]?.href;
    },
    value(data) {
      let value = 0;
      value = data?.bookInfo["pris:ranking"]?.value;
      return value;
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    let {
      id,
      title
    } = options;
    this.setData({
      id,
      title
    });
    this.getBookInfo();
    this.getChapterList();
    await this.getUser();
    this.getComments();
  },
  //获取用户信息
  async getUser() {
    let user = wx.getStorageSync('user') || {};
    let res = await db.collection("user").where({
      _id: user._id
    }).get();
    this.setData({
      user: res.data[0]
    });
  },
  //删除评论
  deleteItem(e) {
    console.log(e.detail);
    this.setData({
      comments:e.detail
    })
  },
  //写评论
  writeComment() {
    console.log(12);
    let user = this.data.user;
    if (!user?.usercode) {
      wx.navigateTo({
        url: '/pages/login/login',
      });
      return;
    };
    wx.navigateTo({
      url: `/pages/comment/comment`,
      events: {
        sendComments: (data) => {
          console.log(data);
          this.setData({
            comments: data.comments
          })
        }
      },
      success: res => {
        console.log(11222);
        res.eventChannel.emit('sendComments', {
          comments: this.data.comments,
          id: this.data.id
        })
      }
    });
  },
  //去章节列表页面
  toChapter() {
    wx.navigateTo({
      url: '/pages/chapter/chapter',
    });
  },
  //书架
  changeBookself() {
    let user = wx.getStorageSync('user');
    if (!user?.usercode) {
      wx.navigateTo({
        url: '/pages/login/login',
      });
      return;
    };
    user.bookself = user.bookself ? user.bookself : [];
    if (!this.data.isInBookself) {
      console.log(user.bookself);
      user.bookself = [this.data.id, ...user.bookself.filter(id => id != this.data.id)];
      wx.setStorageSync('user', user);
      this.setData({
        isInBookself: true
      });
      wx.showToast({
        title: '添加成功',
        icon: "success"
      })
    } else {
      user.bookself = [...user.bookself.filter(id => id != this.data.id)];
      wx.setStorageSync('user', user);
      this.setData({
        isInBookself: false
      });
      wx.showToast({
        title: '移除成功',
        icon: "success"
      })
    }
    wx.cloud.callFunction({
      name: "changeUser",
      data: {
        user
      }
    }).then(res => {
      console.log(res, "res");
    })
  },
  //跳阅读页面
  toRead() {
    let read = wx.getStorageSync('read') || [];
    let list = read.filter(el => el.id == this.data.bookInfo.id);
    let readPage = 0;
    if (list.length) {
      readPage = list[0].readPage;
    }
    wx.navigateTo({
      url: `/pages/read/read?id=${this.data.id}&title=${this.data.title}&uuid=${app.globalData.chapterList[readPage].uuid}`,
    });
  },
  //获取章节列表
  getChapterList() {
    // console.log(app.globalData.chapterList,"chapterlist");
    db.collection(chapterCollection).where({
      id: this.data.id
    }).get().then(res => {
      if (res.data.length) {
        app.globalData.bookInfo = this.data.bookInfo;
        app.globalData.chapterList = res.data[0].catalog;
      } else {
        wx.request({
          url: `${app.globalData.baseUrlData}/yunyuedu/reader/book/info.json?source_uuid=${this.data.id}`,
          method: "GET",
          success: (res) => {
            let data = res.data.data;
            data.id = this.data.id;
            app.globalData.bookInfo = this.data.bookInfo;
            app.globalData.chapterList = res.data.data.catalog;
            wx.cloud.callFunction({
              name: "addChapter",
              data: {
                collection: chapterCollection,
                chapter: data
              }
            });
          }
        })
      }
    })
  },
  //获取评论信息
  getComments() {
    db.collection("comments").where({
      id: this.data.id
    }).get().then(res => {
      if (res?.data[0]?.comments) {
        this.setData({
          comments: res.data[0].comments
        });
      } else {
        wx.request({
          url: `${app.globalData.baseUrlData}/yunyuedu/comment/getComments.json?bookId=${this.data.id}`,
          method: "GET",
          success: (res) => {
            this.setData({
              comments: res.data.all.list
            });
            wx.cloud.callFunction({
              name: "addComments",
              data: {
                id: this.data.id,
                comments: this.data.comments,
                type: "add"
              }
            });
          }
        });
      }
    });
  },
  //获取书籍详情
  getBookInfo() {
    db.collection("books").where({
      id: this.data.id
    }).get().then(res => {
      if (!res?.data?.length) {
        wx.request({
          url: `${app.globalData.baseUrlData}/yunyuedu/book/getsub.json?id=${this.data.id}&title=${this.data.title}`,
          method: "GET",
          success: (res) => {
            let read = wx.getStorageSync('read') || [];
            let list = read.filter(el => el.id == res.data.feed.entry.id);
            let readPage = 0;
            if (list.length) {
              readPage = list[0].readPage;
            }
            this.setData({
              bookInfo: res.data.feed.entry,
              readPage
            });
            if (!res?.data?.feed?.entry) return;
            wx.cloud.callFunction({
              name: "addBookInfo",
              data: {
                bookInfo: res.data.feed.entry
              }
            });
          }
        });
      } else {
        let read = wx.getStorageSync('read') || [];
        let list = read.filter(el => el.id == res.data[0].id);
        let readPage = 0;
        if (list.length) {
          readPage = list[0].readPage;
        }
        this.setData({
          bookInfo: res.data[0],
          readPage
        });
      }
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if (this.data.bookInfo?.id) {
      let read = wx.getStorageSync('read') || [];
      let list = read.filter(el => el.id == this.data.bookInfo.id);
      let readPage = 0;
      if (list.length) {
        readPage = list[0]?.readPage || 0;
      }
      this.setData({
        readPage
      });
    }
    let user = wx.getStorageSync('user') || {};
    if (user?.bookself) {
      let list = user.bookself.filter(value => value == this.data.id);
      this.setData({
        isInBookself: list?.length > 0 ? true : false
      });
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})